package com.dragonfly.shutter.services;

import java.util.Date;
import java.util.List;

import com.dragonfly.shutter.DAOs.AlbumDAO;
import com.dragonfly.shutter.DAOs.BrowseLogDAO;
import com.dragonfly.shutter.DAOs.PictureAlbumDAO;
import com.dragonfly.shutter.DAOs.PictureDAO;
import com.dragonfly.shutter.beans.Album;
import com.dragonfly.shutter.beans.BrowseLog;
import com.dragonfly.shutter.beans.PictureDetail;

/**
 * 删除图片服务类
 * @author 黄挺
 *
 */
public class DeletePictureService {
	private BrowseLogDAO browseLogDAO;
	private PictureDAO pictureDAO;
	private PictureAlbumDAO pictureAlbumDAO;
	private AlbumDAO albumDAO;

	/**
	 * 删除图片的服务函数
	 * @param picture 要删除的图片
	 * @param requestURL 请求的URL
	 * @throws Exception 
	 */
	public void doService(String pictureID, String requestURL) throws Exception {
		// TODO Auto-generated method stub
		PictureDetail picture = new PictureDetail();
		picture.setPictureID(pictureID);
		picture.setFlagDelete("deleted");
		
		doDBOpertate(picture, requestURL);
	}
	
	/**
	 * 删除图片的数据库操作类,记录日志，更新删除标记位，删除图片相册对应关系
	 * @param picture 要删除的图片
	 * @param requestURL 请求的URL
	 * @throws Exception 
	 */
	public void doDBOpertate(PictureDetail picture, String requestURL) throws Exception {
		BrowseLog browseLog = new BrowseLog();
		browseLog.setUserID(picture.getPicOwner().getUserID());
		browseLog.setBrowseTime(new Date(System.currentTimeMillis()));
		browseLog.setUrl(requestURL);
		
		browseLogDAO.insertBrowseLog(browseLog);
		
		if ( pictureDAO.updatePictureDelFlag(picture) == 0 )
			throw new Exception("更新失败，您要删除的图片不存在");
		
		pictureAlbumDAO.deletePicAlbumByPicId(picture.getPictureID());
		List<Integer> albumIDs = pictureAlbumDAO.selectAlbumIdByPictureId(picture.getPictureID());
		
		for ( Integer albumID : albumIDs ){
			Album album = albumDAO.selectAlbumByID(albumID);
			album.setPictureCount(album.getPictureCount() - 1);
			albumDAO.updatePictureCount(album);
		}
	}

	public BrowseLogDAO getBrowseLogDAO() {
		return browseLogDAO;
	}

	public void setBrowseLogDAO(BrowseLogDAO browseLogDAO) {
		this.browseLogDAO = browseLogDAO;
	}

	public PictureDAO getPictureDAO() {
		return pictureDAO;
	}

	public void setPictureDAO(PictureDAO pictureDAO) {
		this.pictureDAO = pictureDAO;
	}

	public void setPictureAlbumDAO(PictureAlbumDAO pictureAlbumDAO) {
		this.pictureAlbumDAO = pictureAlbumDAO;
	}

	public void setAlbumDAO(AlbumDAO albumDAO) {
		this.albumDAO = albumDAO;
	}
}
